//
//  CZUserAccount.swift
//  Weibo
//
//  Created by 铭铭 on 15/11/29.
//  Copyright © 2015年 itcast. All rights reserved.
//

import UIKit

//归档和解档,实现 NSCoding 协议

class CZUserAccount: NSObject, NSCoding{

    /// 用于调用access_token，接口获取授权后的access token。
    var access_token:String?
    
    /// access_token的生命周期，单位是秒数。在KVC字典转模型基本数据类型需要设置初始值.
    var expires_in:NSTimeInterval=0{
        didSet{
            // 设置过期时间
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 保存过期时间NSDate
    var expiresDate: NSDate?
    
    /// 当前授权用户的UID。
    var uid: String?
    
    // 字典转模型,逐个属性赋值
    init( dict:[String : AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
    }
    // 当字典的key在模型中没有对应的属性
    override func setValue(value: AnyObject?, forKey key: String) {}
    
//    调试模型信息 ,打印信息
    override var description: String {
        let properties = ["access_token", "expires_in", "uid","expiresDate"]
        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    
    /**
    *  实现NScode协议方法
    */
    //归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
    }
    ///  解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")

    }
    //定义归档路径
     static let accountPatch = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("account.plist")
    
    /**
    *  保存账户信息
    */
    func saveAccount(){
        
        NSKeyedArchiver.archiveRootObject(self, toFile: CZUserAccount.accountPatch)
    }
    
    /**
    *  解档加载账户信息
    */
    /// 内存中的账户
    private static var userAccount:CZUserAccount?
    
//     读取 保存在沙盒里面的账户信息
    class func loadAccount() -> CZUserAccount?{
        
        if userAccount==nil{
           // 内存中没有账户, 到沙盒加载一个账户(有可能加载出来也有可能加载不出来),赋值给内存中的账户
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPatch) as? CZUserAccount
        print("从沙盒加载账户:\(userAccount)")
        } else {
            print("直接从内存中获取到账户")
        }
           // 2.判断内存中是否有用账户,有账户,判断时间是否过期
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
              // 有账户并且没有过期,是一个可用的账户
                return userAccount
        }
        
//        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPatch) as? CZUserAccount{
//            if account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
//            print("没有过期")
//                return account
//            }
        
//        }
        return nil
    }
    
}
